package com.hongye.why.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.hongye.why.Manifest;
import com.hongye.why.base.ActivityStack;
import com.hongye.why.base.AsyncRunnable;
import com.hongye.why.base.Life;
import com.hongye.why.base.LifeSubscriber;
import com.hongye.why.base.ParamsFactory;
import com.hongye.why.base.TaskPool;
import com.hongye.why.base.net.IRequest;
import com.hongye.why.base.net.OKManager;
import com.hongye.why.base.net.ResponseHandler;
import com.hongye.why.module.LaunchActivity;
import com.hongye.why.util.ToastUtil;
import com.hongye.why.view.CustomDialog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 版本更新
 */
public class UpdateManager implements ResponseHandler<UpdateManager.UpdateResultJson>, LifeSubscriber {

    public static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;
    /**
     * 检查更新API返回结果
     */
    private UpdateResultJson updateResultJson;

    /**
     * 单例
     */
    private static UpdateManager updateManger;

    /**
     * 是否需要更新
     */
    private boolean needUpdate;

    private UpdateManager() {
    }

    /**
     * 单例
     * @return
     */
    public static UpdateManager updateManager() {
        synchronized (UpdateManager.class) {
            if (updateManger == null) {
                updateManger = new UpdateManager();
            }
            return updateManger;
        }
    }

    /**
     * 是否需要更新
     * @return boolean
     */
    public boolean isNeedUpdate() {
        return needUpdate;
    }

    /**
     * 是否有更新版本
     * @return
     */
    public boolean hasNewVersion(){
        boolean flag = false;
        if ( null!= updateResultJson){
            //注意：可能其他项目的更新标志不是1
            flag = updateResultJson.updateFlag == 1;
        }
        return flag;
    }

    @Override
    public void onNetStart() {

    }

    @Override
    public UpdateResultJson parseResult(String result) {
        return JSON.parseObject(result, UpdateResultJson.class);
    }

    @Override
    public void onSuccess(UpdateResultJson result) {
        this.updateResultJson = result;
        if (this.updateResultJson.updateFlag == 1) { //need update
            Activity activity = ActivityStack.topActivity();
            if (activity instanceof LaunchActivity) {
                needUpdate = true;
            } else {
                needUpdate = false;
                showUpdateDialog(activity);
            }
        }
    }

    @Override
    public void onFail(int code, String errorMsg) {
        ToastUtil.showShortToast(errorMsg);
    }

    @Override
    public void onEnd() {

    }

    /**
     * 检查更新操作
     * @param versionCode 当前版本号
     */
    public void checkVersion(int versionCode) {
        OKManager okManager = OKManager.getManager();
        IRequest iRequest = okManager.addRequest(this, ParamsFactory.getUpdateParams(String.valueOf(versionCode)));
        iRequest.execute(this);
    }

    @Override
    public void attach(Life life) {

    }

    @Override
    public void detach(Life life) {

    }

    /**
     * 弹出更新提示框
     * @param activity
     */
    public void showUpdateDialog(final Activity activity) {
        needUpdate = false;
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
//        builder.setTitle("版本升级");
        builder.setMessage("检查到新版本，是否更新？");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (updateResultJson.forceUpdate == 1) {
                    ActivityStack.finishAll();
                }
            }
        });
        builder.setNegativeButton("确定",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        downloadAPK(activity, updateResultJson.downloadUrl);
                    }
                });
        builder.create().show();
    }

    /**
     * 下载更新包
     * @param activity
     * @param path 下载地址
     */
    private void downloadAPK(final Activity activity, final String path) {
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog(activity);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCancelable(false);
        pd.show();
        TaskPool.myPool().post(new AsyncRunnable<File>() {
            @Override
            public File run() {
                try {
                    return getFileFromServer(path, pd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public void postForeground(File result) {
                pd.dismiss();
                if (result != null) {
                    installApk(activity, Uri.fromFile(result));
                } else {
                    ToastUtil.showShortToast("下载安装更新文件出错");
                }
            }
        });
    }

    /**
     * 从服务器下载 APK
     * @param path 下载地址
     * @param pd 进度提示框
     * @return
     * @throws Exception 网络异常，文件流异常
     */
    private static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            float fileSize = Float.valueOf(conn.getContentLength()) / (1024 * 1024);
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "update.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            float showSize = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                showSize = Float.valueOf(total) / (1024 * 1024);
                //获取当前下载量
                pd.setProgress(total);
                pd.setProgressNumberFormat(String.format("%.2fM/%.2fM", showSize, fileSize));
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 安装 APK
     * @param activity
     * @param fileUri
     */
    protected void installApk(Activity activity, Uri fileUri) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 如果不加无法正常显示安装过程和安装成功提示
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行的数据类型
        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");//编者按：此处Android应为android，否则造成安装不了
        activity.startActivity(intent);
    }

    /**
     * 检查更新返回结果
     * 不同的项目更新标志不一样
     */
    public static class UpdateResultJson implements Serializable {
        public int updateFlag;  // 是否有更新 1-是；0-否
        public int forceUpdate;  // 是否强制用户更新 1-是；0-否
        String currentversioncode;  // 更新版本号
        public String downloadUrl;  // 下载地址
    }
}
